package top.kaoshanji.p3ch13a;

import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.*;

/**
 * 代码清单-p3ch13a-430页a：使用SignedObject类来安全保存对象的示例
 * author kaoshanji
 * ^_^
 * create time 2025/2/8 18:54
 */
public class SaveObject {

    public void saveObject(Serializable obj, Path path) throws NoSuchAlgorithmException, IOException, SignatureException, InvalidKeyException {
        Signature signature = Signature.getInstance("SHA1withDSA");
        KeyPairGenerator keyGenerator = KeyPairGenerator.getInstance("DSA");
        KeyPair keyPair = keyGenerator.generateKeyPair();

        SignedObject signedObj = new SignedObject(obj, keyPair.getPrivate(), signature);
        try (ObjectOutputStream oos = new ObjectOutputStream(Files.newOutputStream(path))){
            oos.writeObject(signedObj);
        }

    }

}
